// #include "littlevgl2rtt.h"
// #include "lv_ext_resource_manager.h"
// #include <rtdevice.h>
// #ifndef _WIN32
//     #include "drv_lcd.h"
// #endif
// #include "gui_app_fwk.h"
// #include "lv_ex_data.h"
// #include "app_mem.h"
#include "log.h"
// #include "lv_freetype.h"
#include "sensor_manager.h"
#include "math.h"
#include "update_light.h"
// 添加环境光传感器相关变量
 int light_level = 0;
 uint8_t current_brightness = 100;
 uint32_t last_light_check_time = 0;
#define LIGHT_CHECK_INTERVAL 100  // 每0.1秒检查一次环境光
// 指数移动平均滤波参数
#define EMA_ALPHA 0.2f  // 调整因子，范围0.1-0.3，值越小滤波越平滑但响应越慢
 float ema_filtered_light = 0.0f;  // 初始化为第一个值或0
 bool ema_initialized = false;



// 应用指数移动平均滤波
 int apply_ema_filter(int new_value)
{
    if (!ema_initialized) {
        ema_filtered_light = (float)new_value;
        ema_initialized = true;
        return new_value;
    }
    
    ema_filtered_light = EMA_ALPHA * new_value + (1.0f - EMA_ALPHA) * ema_filtered_light;
    return (int)ema_filtered_light;
}


/**
  * @brief  使用对数调整算法计算屏幕亮度
  * @param  light_level 环境光强度
  * @retval 屏幕亮度值 (0-100)
  */
 uint8_t calculate_brightness(int light_level)
{
    // 亮度调整参数
    const uint16_t MIN_LIGHT_LEVEL = 0;      // 最小环境光强度
    const uint16_t MAX_LIGHT_LEVEL = 1000;   // 最大环境光强度
    const uint8_t MIN_BRIGHTNESS = 10;       // 最小屏幕亮度
    const uint8_t MAX_BRIGHTNESS = 100;      // 最大屏幕亮度
    const bool USE_LOG_ADJUSTMENT = true;    // 是否使用对数调整
    
    if (light_level <= MIN_LIGHT_LEVEL) return MIN_BRIGHTNESS;
    if (light_level >= MAX_LIGHT_LEVEL) return MAX_BRIGHTNESS; 
    
    float normalized;
    if (USE_LOG_ADJUSTMENT) {
        // 对数调整：压缩高值，扩展低值
        normalized = logf(light_level + 1) / logf(MAX_LIGHT_LEVEL + 1);
    } else {
        // 标准线性
        normalized = (float)(light_level - MIN_LIGHT_LEVEL) / (MAX_LIGHT_LEVEL - MIN_LIGHT_LEVEL);
    }
    
    return (uint8_t)(normalized * (MAX_BRIGHTNESS - MIN_BRIGHTNESS) + MIN_BRIGHTNESS);
}


// 检查环境光并调整亮度
void process_light_data(void)
{
    uint32_t current_time = rt_tick_get();
    if (current_time - last_light_check_time > LIGHT_CHECK_INTERVAL)
    {
        last_light_check_time = current_time;
        
        // 获取环境光数据
        if (get_ltr303_data(&light_level) == 0)
        {
            // 应用指数移动平均滤波
            int filtered_light = apply_ema_filter(light_level);
            
            // 根据环境光调整亮度
            uint8_t new_brightness = calculate_brightness(filtered_light);
            
                // 线性逐步调整亮度
                if (new_brightness != current_brightness)
                {
                    if (new_brightness > current_brightness)
                        current_brightness++;
                    else
                        current_brightness--;
                    rt_device_control(lcd_device, RTGRAPHIC_CTRL_SET_BRIGHTNESS, &current_brightness);
                    //rt_kprintf("Light level: %d, Brightness: %d\n", light_level, current_brightness);
                }
        }
    }
}
